package com.darsystems.foghourz.server;

import java.io.IOException;
import java.util.logging.Logger;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.CDATASection;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import com.darsystems.foghourz.client.FBResponse;

public class FBServiceAPI {

	private final static Logger log = Logger.getLogger(FBServiceAPI.class.getName());
	
	public String getToken(String userName, String password)
	{
		try {
			Document responseDoc = getResponseDoc("logon", "", "email=" + userName + "&password=" + password);
			return parseToken(responseDoc);
		} catch (Exception e) {
			log.warning("Problem logging in: " + e.getMessage());
			return "";
		} 
	}

	public Document getResponseDoc(String cmd, String token, String args) throws Exception,
			IOException, ParserConfigurationException, SAXException {
		
		String fbUrl = FBUserConfigStore.getUserFBServer() + "/api.asp?cmd=" + cmd;

		if(token != null && !token.isEmpty()){
			fbUrl += "&token=" + token;
		}
		
		if(args != null && !args.isEmpty())
		{
			fbUrl += "&" + args;
		}
		
		DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
		DocumentBuilder db = dbf.newDocumentBuilder();
		return db.parse(fbUrl);		
	}

	static public String parseToken(Document doc)
	{
		//<?xml version=\"1.0\" encoding=\"UTF-8\"?><response><token><![CDATA[2pioutnat90k1jejhl10o0kei7l762]]></token></response>
		NodeList tokenNodes = doc.getElementsByTagName("token");
		if(tokenNodes.getLength() != 1)
		{
			FBResponseInternal fbResponse = new FBResponseInternal(doc);
			if(!fbResponse.isOK())
			{
				log.warning("Login failed: " + fbResponse.getFullErrorMessage() );
			}
			else
			{
				log.warning("Login failed, but error was not set!");
			}
			return "";
		}
		
		Element tokenElement = (Element) tokenNodes.item(0);
		NodeList cdataNodes = tokenElement.getChildNodes();
		if(cdataNodes.getLength() != 1)
		{
			log.warning("Login failed - no CDATA section found" );
			return "";
		}
		
		CDATASection cdataNode = (CDATASection)cdataNodes.item(0);
		return cdataNode.getTextContent();
	}
	
	public FBResponseInternal executeCommandInternal(String token, String command, String args) {
		FBResponseInternal fbResponse;
		try {
			fbResponse = new FBResponseInternal(getResponseDoc(command, token, args));

		} catch (Exception e) {
			fbResponse = new FBResponseInternal(e);
		} 
		
		return fbResponse;
	}
	
	public FBResponse executeCommand(String token, String command, String args) {

		return executeCommandInternal(token, command, args).getBaseResponse();
	}
}
